//评论模块路由


var express = require("express");
var router = express.Router();
var { checkSession,dateFormat } = require("../utils/index.js")
var { Mvs, Lists } = require("../utils/model")
router.get("/index", (req, res) => {
  checkSession(req, res, () => {
    var { mid } = req.query;
    var obj = {};

    if (mid) {
      obj = { id: mid }
    }

    const findOneData = function (obj, callback) {
      Mvs.findOne(obj).then(result => {
        callback(result)

      })

    }

    findOneData(obj, (result) => {
      res.render("comment", {
        username: req.session.username,
        result
      })
    })


  })

})
//提交评论
router.post("/submit", (req, res) => {
  const query = req.query;
  const body = req.body;
  console.log(body);
  checkSession(req, res, () => {
    Mvs.findOne({
      id: query.mid
    }).then(movie => {
      body.time = new Date();
      body.author = req.session.username;
      body.mid = query.mid;
      body.movie = movie;
      Lists.insertMany(body)
        .then(result => {
          res.redirect("/comment/lists")
        })
    })
  })

})



//评论列表
router.get("/lists",(req,res)=>{
  checkSession(req,res,()=>{
      // 分页 
      var {
          pageSize,
          page
      } = req.query;
      var total = 0;
      var totalPage = 0;
      pageSize = pageSize *1 || 10;   // 每页的数量
      page = page *1  || 1;   // 页码

      Lists.find({},{})
      .then(data=>{
          total  = data.length;
          totalPage = Math.ceil(total/pageSize);
          page  = page < 1 ? 1 : page;
          page = page > totalPage ? totalPage : page;

          Lists.find({},{})
          .skip((page-1)*pageSize)
          .limit(pageSize)
          .sort({_id:-1})
          .then(result=>{
              result = result.map(item=>{
                  item = {...item._doc,time:dateFormat(item.time)}
                  return item;
              })
              res.render('lists',{
                  username:req.session.username,
                  result,
                  total,
                  page,
                  pageSize,
                  totalPage
              })
          })
      })


      // Comment.find({},{})
      // .sort({_id:-1})
      // .then(result=>{
      //     result = result.map(item=>{
      //         item = {...item._doc,time:dateFormat(item.time)}
      //         return item;
      //     })
      //     res.render('mlist',{
      //         username:req.session.username,
      //         result
      //     })
      // })
  })
})


//当前电影的所有评论
router.get("/moviepin",(req,res)=>{
  checkSession(req,res,()=>{
    var {mid}= req.query;
    Lists.find({mid},{})
    .sort({_id:-1})
    .then(result=>{
      result = result.map(item=>{
        item = {...item._doc,time:dateFormat(item.time)}
        return item;
    })
      res.render("moviepin",{
        result,
        movie:result[0].movie,
        username:req.session.username
      })
    })


  })


  
})

module.exports = router;

